<template>
  <main>
    <div class="main">
      <div>
        <a-carousel :autoplay="true" :adaptiveHeight="true">
          <div v-for="(item, index) in banners" :key="index">
            <a-image class="banner-img" :src="item.cover" />
          </div>
        </a-carousel>
      </div>

      <div class="section-content">
        <div>
          <div class="search-input-wrapper">
            <a-input-search placeholder="请输入关键字" :allowClear="true" v-model="searchKeywords" @focus="inputSearchOnFocus" @change="inputSearchChange" @blur="inputSearchOnBlur" @pressEnter="searchPressEnter" />
          </div>
          <div v-if="keywords && Array.isArray(keywords) && keywords.length > 0" class="search-container">
            <h4 class="search-headline">#热搜</h4>
            <span v-if="keywords">
              <a-tag class="tag" v-for="(item, index) in keywords" :key="index" @click="keywordClick(item)">
                {{ item.keyword }}
              </a-tag>
            </span>
          </div>
        </div>

        <div>
          <menu-bar-pc :selectedIndex.sync="selectedIndex" :items="categories" :itemClick="menuItemClick"></menu-bar-pc>
        </div>

        <div class="collection-news">
          <div class="cell" v-for="(item, index) in items" :key="index" @click="itemClick(item)">
            <div class="container">
              <a-image :src="item.cover" />
              <div class="text">
                <div>
                  <h4 class="news-cell-headline">{{ item.name }}</h4>
                  <v-clamp class="news-cell-subhead" autoresize :max-lines="newsSubheadMaxLines">{{ item.subname }}</v-clamp>
                </div>
                <div class="status-bar date-source">
                  <p>
                    来源：<span class="source">{{ item.source }}</span>
                  </p>
                  <p class="time-text">发布时间：{{ item.createTime }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <a-pagination background layout="prev, pager, next" :current="currentPage" :page-size="pageSize" :total="totalCount" @change="paginationOnChange"> </a-pagination>
      </div>
    </div>
  </main>
</template>

<script>
import { mapState, mapActions } from "vuex";

export default {
  name: "List",
  data() {
    return {
      selectedIndex: 0,
      searchKeywords: "",
      isSearchInputing: false,
      categoryId: undefined,
    };
  },

  components: {},

  computed: {
    newsSubheadMaxLines: function () {
      return document && document.documentElement.clientWidth >= 1920 ? 2 : 1;
    },
    ...mapState("news", {
      categories: (state) => state.categories,
      keywords: (state) => state.keywords,
      items: (state) => state.items,
      pageSize: (state) => state.pageSize,
      pageTotal: (state) => state.pageTotal,
      totalCount: (state) => state.totalCount,
      currentPage: (state) => state.currentPage,
      originalPage: (state) => state.originalPage,
    }),

    ...mapState("banner", {
      banners: (state) => state.newsBanners,
    }),
  },

  created() {
    document.title = "资讯中心";
    const that = this;
    const query = this.$route.query;
    console.log("\n\n query categoryId :" + JSON.stringify(query.categoryId) + "\n\n");
    if (query && query.categoryId) {
      this.categoryId = query.categoryId;
    }

    this.getNewsBannerListAction().catch((error) => {
      that.$message.error(error.message);
    });
    this.getNewsCategoryListAction({ pageNo: 1, pageSize: 99 });

    this.getNewsSearchListAction({ pageNo: 1, pageSize: 99 })
      .then(() => {
        that.updateSelectedIndex();
        that.updateList();
      })
      .catch((error) => {
        that.$message.error(error.message);
      });
  },

  methods: {
    ...mapActions("news", ["getNewsCategoryListAction", "getNewsSearchListAction", "getNewsListAction", "updateCurrentPageAction", "updateOriginalPageAction"]),
    ...mapActions("banner", ["getNewsBannerListAction"]),

    updateSelectedIndex() {
      if (this.categoryId && this.categories && Array.isArray(this.categories) && this.categories.length > 0) {
        console.log("\n\n" + "inside selected index" + "\n\n");
        const results = this.categories.filter((c) => c.id == this.categoryId);
        if (results && Array.isArray(results) && results.length > 0) {
          const category = results[0];
          this.selectedIndex = this.categories.indexOf(category);
          console.log("\n\n selectedIndex:" + JSON.stringify(this.selectedIndex) + "\n\n");
        }
      }
    },

    keywordClick(item) {
      this.searchKeywords = item.keyword;
      this.updateList();
    },

    menuItemClick(item, index) {
      this.selectedIndex = index;
      this.updateCurrentPageAction(1);
      this.updateList();
    },

    itemClick(item) {
      this.$router.push({
        path: "/news/detail",
        query: { id: item.id },
      });
    },

    /**
     * @description: 输入框编辑聚焦(开始编辑)
     * @param {*}
     * @return {*}
     */
    inputSearchOnFocus() {
      if (!this.searchKeywords) {
        this.updateOriginalPageAction(this.currentPage);
      }
      this.updateCurrentPageAction(1);
      this.isSearchInputing = true;
    },

    /**
     * @description: 输入文本变化监听，可以用于Autocomplete的实现
     * @param {*}
     * @return {*}
     */
    inputSearchChange() {
      if (this.isSearchInputing == false) {
        if (!this.searchKeywords) {
          console.log("\n\n this.originalPage = " + JSON.stringify(this.originalPage) + "\n\n");
          this.updateCurrentPageAction(this.originalPage);
          this.updateList();
        }
      }
    },

    /**
     * @description:输入框失去编辑聚焦
     * @param {*}
     * @return {*}
     */
    inputSearchOnBlur() {
      console.log("\n\n inputSearchOnBlur this.originalPage = " + JSON.stringify(this.originalPage) + "\n\n");
      this.isSearchInputing = false;
      this.updateList();
    },

    /**
     * @description: 键盘enter事件监听
     * @param {*}
     * @return {*}
     */
    searchPressEnter() {
      console.log("\n\n searchPressEnter this.originalPage = " + JSON.stringify(this.originalPage) + "\n\n");
      this.updateList();
    },

    paginationOnChange(value) {
      this.updateCurrentPageAction(value);
      this.updateList();
    },

    updateList() {
      const that = this;
      const item = this.categories[this.selectedIndex];
      var categoryId = null;
      if (item) {
        categoryId = item.id;
      }
      const parameters = {
        pageSize: this.pageSize,
        pageNo: this.currentPage,
        // categoryId: this.searchKeywords ? null : categoryId,
        categoryId: categoryId,
        name: this.searchKeywords,
      };
      const isRefresh = true;
      const isPC = true;
      this.getNewsListAction({ isRefresh, parameters, isPC }).catch((error) => {
        that.$message.error(error.message);
      });
    },
  },
};
</script>

<style scoped lang="less">
.search-input-wrapper {
  padding: var(--padding-xxx-small) 0;
}

.search-headline {
  padding: 10px 10px;
  white-space: nowrap;
}

.search-container {
  display: flex;
  flex-direction: row;
  width: 50% !important;
  margin: 10px auto;
  padding: 10px 0px;
  align-items: flex-start;
}
.search-container .tag {
  margin: var(--margin-xxx-small) var(--margin-xxx-small);
}

.collection-news {
  width: auto;
}

.date-source {
  color: rgba(0, 0, 0, var(--r-opacity-secondary));
  display: flex;
  flex-direction: row !important;
  justify-content: flex-start !important;
  padding: var(--padding-xxx-small) 0px;
  margin: var(--margin-small) 0px;
}
.date-source .source {
  margin-right: var(--margin-small);
  color: var(--r-primary-color);
}
</style>
